#include "touch.h"
Touch* Touch::m_instance = NULL;
int Touch::fd = -1;
Touch::Touch(const char *dev_path)
{
    this->fd = open(dev_path, O_RDONLY);
    if (this->fd < 0)
    {
        perror("[error] touch open");
        exit(1);
    }
}
Touch::~Touch()
{

}
Touch *Touch::instance(const char *dev_path)
{
    if(m_instance == NULL)
    {
        m_instance = new Touch(dev_path);
    }
    return m_instance;
}
void Touch::del_instance()
{
    ::close(Touch::fd);
    delete m_instance;
}
void Touch::wait(Point &p)
{
    while(1)
    {
        struct input_event info;//定义结构体获取数据
        read(this->fd, &info, sizeof(info));//读取数据
        //判断当前发生的是触摸屏事件,接着判断触发的是X轴事件
        if(info.type == EV_ABS && info.code == ABS_X)
        {
            p.setX(info.value*800/1024);
        }
        //判断当前发生的是触摸屏事件,接着判断触发的是Y轴事件
        if(info.type == EV_ABS && info.code == ABS_Y)
        {
            p.setY(info.value*480/600);
        }
        //松开的时候退出循环
        if(info.type == EV_KEY && info.code == BTN_TOUCH &&  info.value == 0)
        {
            break;
        }
    }
}
// 改进的触摸检查函数
bool Touch::check(Point& p) 
{
    fd_set readfds;
    FD_ZERO(&readfds);
    FD_SET(fd, &readfds);

    struct timeval tv = {0, 0};
    int ret = select(fd + 1, &readfds, NULL, NULL, &tv);
    if (ret <= 0) {
        return false; // 无数据或错误
    }

    // 使用局部变量，避免静态变量的状态问题
    int x = -1, y = -1;
    bool isPressed = false;
    bool gotCompleteEvent = false;

    // 读取所有可用的事件
    struct input_event info;
    ssize_t bytesRead;
    while ((bytesRead = read(fd, &info, sizeof(info))) == sizeof(info)) 
    {
        // 处理触摸按下
        if (info.type == EV_KEY && info.code == BTN_TOUCH) {
            if (info.value == 1) {
                // 按下事件
                isPressed = true;
                x = -1;
                y = -1;
            } else if (info.value == 0) {
                // 松开事件
                isPressed = false;
                if (x != -1 && y != -1) {
                    p.setX(x);
                    p.setY(y);
                    gotCompleteEvent = true;
                    break; // 得到一个完整点击，立即返回
                }
            }
        }

        // 处理坐标（只在按下状态时记录）
        if (isPressed) {
            if (info.type == EV_ABS && info.code == ABS_X) {
                x = info.value * 800 / 1024;
            } else if (info.type == EV_ABS && info.code == ABS_Y) {
                y = info.value * 480 / 600;
            }
        }
    }

    // 处理读取错误（非EAGAIN）
    if (bytesRead == -1 && errno != EAGAIN) {
        perror("触摸设备读取错误");
    }

    return gotCompleteEvent;
}